package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebServlet("/goodsServlet")
public class GoodsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 1.获取所有cookie
        Cookie[] cookies = request.getCookies();

        // 2.取出浏览的商品名
        String good = request.getParameter("good");

        // 3.遍历
        for (Cookie cookie : cookies) {
            //4.取出每一个cookie名字
            String name = cookie.getName();
            if("history".equals(name)){
                // 获取cookie存储的值
                String value = cookie.getValue();
                // 将cookie的多个值以-分割成数组
                String[] arr = value.split("_");
                // 将数组变成集合
                List<String> list = Arrays.asList(arr);
                // 判断商品是否存在集合中,不存在，则将商品存储到cookie中
                if(!list.contains(good)){
                    value = value +"_"+good;
                    //将新的value覆盖之前的value
                    cookie.setValue(value);
                    // 将新的cookie响应到浏览器中
                    response.addCookie(cookie);
                }



            }else {
                // 第一次浏览；将浏览商品名存储到cookie中
                Cookie cookieGood = new Cookie("history", good);
                // 将cookie响应给浏览器
                response.addCookie(cookieGood);

            }
        }
    }
}
